# coding=utf-8
from mongoengine import *
from flask import Flask,jsonify,request
from bson.json_util import dumps
from util import getUserList,removeUser,addUser,userEdit
import json
#mongodb part
conn = connect('user')

class user(Document):
    username = StringField()
    password = StringField()
    name = StringField()
    avatar = StringField()
    #id = IntField()
#class userlist(Document):
#    name = StringField()
#    addr = StringField()
#    birth = StringField()
#    sex = StringField()    
#new = user()
#new.username="luoyingli"
#new.password="123456"

#new.save()
def legal(username,password):
    msg=""
    code=200
    if isinstance(username,str) and isinstance(password,str):
        name=user.objects(username=username)
        if name:
            if name[0].password==password:
                msg={"name":name[0].name,
                     "avatar":name[0].avatar,
                     "id":name[0].id,
                     }
            else:
                msg = "password is wrong"
                code = 403
        else:
            msg = "the user does not exists"
            code = 403
            
    else:
        msg = "the input of password or user is illegal"
        code = 403
    return code,msg
# legal("huzhengi","1234567")
#for user in user.objects(username='luoyingli'):
#    print user.username
#print dir(user.objects(username='luoyingli'))

#flask part

app=Flask(__name__)

@app.route("/login",methods=["POST","GET","PUT"])
def login():
    req=request.get_json()
    #uname=str(request.form.get('username'))
    #pwd=str(request.form.get('password'))
    uname=str(req["username"])
    pwd=str(req["password"])
    print "username:",uname
    print type(uname)
    print "password:",pwd
    print type(pwd)
    code,msg = legal(uname,pwd)
    user={"id":1,
          "username":uname,
          "avatar":"https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png",
          "name":"胡正"
          }
    if code==200:return jsonify({"code":200,"msg":'请求成功',"user":msg}),code
    else:return msg,code
@app.route("/user/list",methods=["GET"])
def getUserList_new():
#    User=[]
#    result = userlist.objects.all()
#    print result
#    print dumps(.find(userlist.objects._query))
#    print "userlist:",type(userlist)
#    print "userlist.objects:",type(userlist.objects)
#    print "userlist.objects.all():",type(userlist.objects.all())
#    print "userlist.objects():",type(userlist.objects())
#    print "userlist.objects()._collection_obj:",userlist.objects()._collection_obj
#    print userlist.objects()._query
 #   Users=result._collection_obj.find()  #get the cursor
 #   res=eval(dumps(Users))
 #   for i in res:i.pop("_id")
 #   print res
 #   for user in result:
 #       User.append(user.to_json(use_db_field=False))
    mockuser=[{"id":1,
             "sex":1,
             "age":26,
             "name":"huzheng",
             "addr":"china",
             "birth":"1991-01-08"},
             {"id":1,
             "sex":1,
             "age":24,
             "name":"luoyingli",
             "addr":"china",
             "birth":"1993-07-27"}
             ]
    return jsonify({"users":getUserList()}),200
@app.route("/user/listpage") 
def getListPage_new():
    name=request.args.get("name")
    ulist=getUserList(name)
    count = len(ulist)
    print "in getlistpage:"
    print count
    try:
        page = int(request.args.get('page'))
    except Exception:pass
    if not isinstance(page,int):return jsonify([]),403
    res=[]
    if page<1:return jsonify([]),403
    else:
        if (page-1)*20>count:return jsonify([]),403
        else:
            if count>=20*page:res = ulist[20*(page-1):20*page]
            else:res=ulist[20*(page-1):]
    return  jsonify({"total":count,"users":res}),200
@app.route("/user/remove")
def removeUser_new():
    if removeUser(int(request.args.get("id"))):
        return jsonify({"code":200,"msg":"删除成功"}),200
    else:return jsonify({"code":500,"msg":"错误"}),500
@app.route("/user/add")
def addUser_new():
    ulist=getUserList()
    count = len(ulist)
    name=request.args.get("name")
    sex=request.args.get('sex')
    addr=request.args.get('addr')
    age=request.args.get('age')
    birth=request.args.get('birth')

    if addUser(name,sex,addr,age,birth):
        return jsonify({"code":200,"msg":"添加成功"}),200
    else:return jsonify({"code":500,"msg":"添加失败"}),500
@app.route('/user/edit')
def userEdit_new():
    ulist=getUserList()
    count = len(ulist)
    name=request.args.get("name")
    sex=request.args.get('sex')
    addr=request.args.get('addr')
    age=request.args.get('age')
    birth=request.args.get('birth')
    id=request.args.get('id')
    if userEdit(name,int(sex),addr,int(age),birth,int(id)):
        return jsonify({"code":200,"msg":"编辑成功"}),200
    else:return jsonify({"code":500,"msg":"编辑失败"}),500
@app.route('/user/batchremove')
def batchRemove_new():
    ids=[int(i) for i in request.args.get("ids").split(",")]
    errs=[]
    for id in ids:
        if removeUser(id):pass
        else:errs.append(id)
    if errs:
        print "删除失败用户id:"+str(errs)
        return jsonify({"code":500,"msg":"全部或部分用户删除失败"}),500
    else:
        return jsonify({"code":200,"msg":"删除成功"}),200


if __name__=="__main__":
    app.run()
    
